# Copyright (C) 2009 The Written Word, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# $Id$

import os

from urlparse import urlparse, urlunparse

# This is just an initial list of packages which might contain duplicates.
# We do not create the package objects as we add the package names because
# we do not yet know what package type we will use. So, we add all package
# names first then create package_list[] with the objects later.
class PackageNames (list):
  """A list of PackageName instances

  PackageNames extends the built-in list type.
  """
  def append (self, name, file = None):
    """Append a newly created PackageName instance.

    @param name: The name of the package, or a url to locate it.
    @param file: If name is just a name, file is the path to the package.
    """
    super (PackageNames, self).append (PackageName (name, file))


class PackageName (object):
  """A name for a package and optional file, with some useful methods

  PackageName might have a url in the name field.
  """
  def __init__ (self, name, file = None):
    self.name = name
    self.file = file

    self._url = urlparse (name, 'file')

  def __str__ (self):
    return self.geturl ()

  def __path_to_url (self, path):
    """Helper method factoring common code from geturl() and
       remote_depot()"""
        
    url = (self._url.scheme, self._url.netloc, path, '', '', '')
    return urlunparse (url)

  def getscheme (self):
    return self._url.scheme

  def geturl (self):
    return self.__path_to_url (self._url.path)

  def isfile (self):
    if self._url.scheme == 'file':
      return os.path.isfile (self._url.path)
    else:
      return False

  def normpath (self):
    if not self.isfile ():
      # Can't reliably normalise a regular url...
      return None
        
    if os.path.isabs (self._url.path):
      path = self._url.path
    else:
      path = os.path.join (os.getcwd (), self._url.path)

    return os.path.normpath (path)

  def basename (self):
    return os.path.basename (self._url.path)

  def remote_depot (self):
    return self.__path_to_url (os.path.dirname (self._url.path))

  def remote_path (self):
    return self._url.path

